import jwtDecode from 'jwt-decode'
import Vue from 'vue'
import VueRouter from 'vue-router'
// import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'Login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue')
  },
  {
    path: '/menu',
    name: 'menu',
    component: () => import('../views/menu.vue'),
    children: [
      {
        path: '/menu/',
        name: 'home',
        component: () => import('../views/home.vue'),
      },
      {
        path: '/menu/money',
        name: 'money',
        component: () => import('../views/money.vue'),
      },
      {
        path: '/menu/info',
        name: 'info',
        component: () => import('../views/info.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  
  if (to.path === "/" || to.path ==="/register" ) return next()
  let token = localStorage.getItem('token') || ''
  if (to.path === '/' && token != '') return next()
  if (to.path !== '/' && token == '') return next('/')
  
  if (!token) {
    return next("/")
  }
  let { exp, name } = jwtDecode(token);
  let nowtime = new Date().getTime()
  nowtime = Math.floor(nowtime / 1000)
  if (exp - nowtime >= 0) {
    next()
  } else {
    next('/')
  }
});

export default router
